package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"jd-mall/jd_srv/internal/svc"
	"jd-mall/jd_srv/jd_srv"
	"jd-mall/jd_srv/jdsrvclient"
	"jd-mall/models/mysql"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *jd_srv.ShopListRequest) (*jd_srv.ShopListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var ShopsList []mysql.ShopList
	mysql.DB.Table("shops").
		Select("shops.*,shop_images.*").
		Joins("left join shop_images on shop_images.id = shops.id").
		Limit(int(pageSize)).Offset(int(offset)).
		Where("shop_status = 1").
		Find(&ShopsList)
	var list []*jdsrvclient.ShopList
	for _, List := range ShopsList {
		slice := jdsrvclient.ShopList{
			Id:            int64(List.Id),
			ShopImage:     List.ShopImage,
			ShopName:      List.ShopName,
			ShopDesc:      List.ShopDesc,
			ShopPrice:     float32(List.ShopPrice),
			ShopInventory: int64(List.ShopInventory),
			ShopStatus:    int64(List.ShopStatus),
		}
		list = append(list, &slice)
	}
	return &jd_srv.ShopListResponse{
		List: list,
	}, nil
}
